﻿using UnityEngine;
using System.Collections;

public class Vehicle2DBehaviourScript : MonoBehaviour
{
    [Tooltip("质量")]
    public float mass = 1;
    [Tooltip("最大速度")]
    public float maxSpeed = 10;
    [Tooltip("最大转角")]
    public float maxRurnRate = 1;
    [Tooltip("巡逻圈距离")]
    public float wanderDistance = 0.5f;
    [Tooltip("巡逻圈半径")]
    public float wanderRadius = 0.5f;
    [Tooltip("操控脚本")]
    public Steering2DBehavious steering2D;

    [HideInInspector]
    public Vector2 velocity { get; private set; }
    public Vector2 heading { get; private set; }
    public Vector2 side { get; private set; }
    public float speed { get { return velocity.magnitude; } }
    public float speedSq { get { return velocity.sqrMagnitude; } }
    public float deltaTime { get { return Time.deltaTime; } }
    public Vector2 pos2d
    {
        get
        {
            var pos3 = transform.position;
            return new Vector2(pos3.x, pos3.y);
        }
        set
        {
            var pos3 = new Vector3(value.x, value.y, transform.position.z);
            transform.position = pos3;
        }
    }

    // Use this for initialization
    void Start()
    {
        velocity = Vector2.zero;
        heading = Vector2.zero;
        side = Vector2.zero;
    }

    void FixedUpdate()
    {
        // 力
        var steeringForce = steering2D.Calculate();
        // 加速度
        var acceleration = steeringForce / mass;
        // 更新速度
        velocity += acceleration * deltaTime;

        // 确保最大速度
        velocity.Truncate(maxSpeed);

        // 更新位置
        pos2d += (velocity * deltaTime);

        // 如果速度远大于一个很小值 那么更新朝向
        if (velocity.sqrMagnitude > 0.0000001)
        {
            heading = velocity.normalized;
            side = heading.Perp();
        }

    }
}
